﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using KamRemakeRemake.GameObjects.UnitObjects.Units;

namespace KamRemakeRemake.GameObjects.UnitObjects.Actions.BattleActions
{
    public class Walk : UnitAction
    {
        private Vector2? targetPosition;
        public Vector2 TargetPosition 
        {
            get { return targetPosition.HasValue ? targetPosition.Value : Unit.CurrentPosition; }
            set { targetPosition = value; }
        }

        private Direction? targetDirection;
        public Direction TargetDirection 
        {
            get { return targetDirection.HasValue ? targetDirection.Value : Unit.CurrentDirection; }
            set { targetDirection = value; }
        }

        private int? speed;
        private int Speed
        {
            get 
            {
                if (CanExecute)
                {
                    speed = Unit.UnitSpeed;
                }

                return speed.HasValue ? speed.Value : 0;
            }
            set 
            {
                Unit.CurrentSpeed = 0;
            }
        }

        protected override bool CanExecute
        { get { return TargetPosition != null && Unit != null && Unit.CurrentPosition != TargetPosition; } }

        public Walk()
        {
            SpriteSuffix = "walk";
        }
        
        /// <summary>
        /// move the unit to the target location if that cant be done, hold the unit
        /// </summary>
        /// <param name="gameTime"></param>
        public override void Update(GameTime gameTime)
        {
            if (CanExecute)
            { 
                float newXPosition = Unit.CurrentPosition.X;
                if(Unit.CurrentPosition.X < TargetPosition.X)
                {
                    newXPosition = Unit.CurrentPosition.X + Speed;
                }
                else if(Unit.CurrentPosition.X > TargetPosition.X)
                {
                    newXPosition = Unit.CurrentPosition.X - Speed;
                }

                float newYPosition = Unit.CurrentPosition.Y;
                if(Unit.CurrentPosition.Y < TargetPosition.Y)
                {
                    newYPosition = Unit.CurrentPosition.Y + Speed;
                }
                else if(Unit.CurrentPosition.Y > TargetPosition.Y)
                {
                    newYPosition = Unit.CurrentPosition.Y - Speed;
                }

                Unit.CurrentPosition = new Vector2(newXPosition, newYPosition);

                base.currentSprite.Update(gameTime);
            }
            else
            {
                Speed = 0;
            }
        }
    }
}
